﻿using Newtonsoft.Json;
using PanhuaWin.WMS2NC888;
using PanhuaWin.系统管理;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;

namespace PanhuaWin.仓库.采购入库
{
    public partial class Form原料卷入库审核 : UIPage
    {
        public string docCode;
        public string workshopCode;
        public string 仓库名称 = "原料库";
        public Form原料卷入库审核()
        {
            InitializeComponent();
        }

        private void Form原料卷入库审核_Load(object sender, EventArgs e)
        {
            this.uiDatePicker开始日期.Value = DateTime.Today.AddMonths(-1);
            this.uiDatePicker结束日期.Value = DateTime.Today;
            pub.ListWorkShop(pub.sys_user, this.uiComboBoxWorkShop);
        }

        private void uiButton合同查询_Click(object sender, EventArgs e)
        {
            ListData();
            this.uiDataGridView合同原料卷.DataSource = null;
            this.uiDataGridView合同原料卷.Refresh();
          

        }

        private void ListData()
        {
            string sql;
            workshopCode = this.uiComboBoxWorkShop.SelectedValue.ToString();
            sql = @"SELECT     guid, StockInType, WorkShopCode, DocCode, DepartCode, CreateID, Creator, CreateDate, ModifyID, Modifier, 
                ModifyDate, ApproverID, Approver, ApproverDate, IsSendToNC, SendToNCDate
FROM      Bus_StockInV where 1=1 ";
            sql += " and CreateDate>='" + this.uiDatePicker开始日期.Value + "' and CreateDate< '" + this.uiDatePicker结束日期.Value.AddDays(1) + "'";
            sql += " and WorkShopCode ='" + workshopCode + "'";
            if (!this.uiCheckBox已审核.Checked)
            {
                sql += " and (ApproverID is null or ApproverID ='') ";
            }
            sql += " and StockInType='原料卷入库'";
            sql += " order by CreateDate ";
            DataTable tb1 = pub.GetDataTable(pub.ConnectionString, sql);
            this.uiDataGridView原料入库单.AutoGenerateColumns = false;
            this.uiDataGridView原料入库单.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
            this.uiDataGridView原料入库单.DataSource = tb1;
            this.uiDataGridView原料入库单.Refresh();
        }

        private void uiDataGridView合同原料卷_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0)
            {


                if (this.uiDataGridView合同原料卷.Columns[e.ColumnIndex].Name == "D删除")
                {
                    if (MessageBox.Show("您要删除这一行么") == DialogResult.OK)
                    {
                        string bguid = this.uiDataGridView合同原料卷.Rows[e.RowIndex].Cells["DBguid"].Value.ToString();
                        
                        string VolumeCode = this.uiDataGridView合同原料卷.Rows[e.RowIndex].Cells["D原料卷号"].Value.ToString();
                        //检查是不是审批了
                        if (!pub.IsExistVolume(VolumeCode))
                        {

                            MessageBox.Show("原料卷号不存在，不能删除!", "提示", MessageBoxButtons.OK);
                            return;
                        }
                        if (pub.IsVolumeApproved(VolumeCode))
                        {
                            MessageBox.Show("原料卷已经审核，不能删除!", "提示", MessageBoxButtons.OK);
                            return;
                        }
                        if (pub.IsPurchaseVolumeBeUsed(workshopCode,VolumeCode))
                        {
                            MessageBox.Show("原料卷已经使用，不能删除!", "提示", MessageBoxButtons.OK);
                            return;
                        }
                        ///开始删除
                        if (pub.Delete原料入库行(bguid) > 0)
                        {
                            List原料行信息(docCode, this.uiDataGridView合同原料卷);
                        }

                    }

                }
            }
           
        }

        /// <summary>
        /// 根据单号 看明细
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void uiDataGridView原料入库单_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
          
            //for (int i = 0; i < uiDataGridView合同原料卷.Rows.Count; i++)
            //{
            //    if (uiDataGridView合同原料卷.Rows[i].Cells["D合同号"].Value.ToString()!=""&& uiDataGridView合同原料卷.Rows[i].Cells["D合同行号"].Value.ToString()!="")
            //    {
                  
            //        uiDataGridView合同原料卷.Rows[i].ReadOnly=true  ;
            //    }
            //    else
            //    {
            //        uiDataGridView合同原料卷.Rows[i].ReadOnly = false;
            //    }
            //}
        }

        private void uiDataGridView原料入库单_CellClick(object sender, DataGridViewCellEventArgs e)
        {

        }


        private void List原料行信息(string doccode, UIDataGridView uiDataGridView)
        {
            string sql;
            //            sql = @"SELECT  Bus_StockInVolume.guid, Bguid, DocCode, RowNumber, WorkShopCode, WarehouseCode, StorageLocation, T_CONTRACT_CODE, 
            //                T_ORDER, Bus_StockInVolume.T_GOOD_UNIT, T_GOOD_NUM, T_GOOD_PRICE, T_GOOD_MONEY, VolumeCode, InventoryCode, Size, 
            //                Thick, Width, Material, Weight, CID, Virtual,Address,VolumeCodeNew ,T_VIEW_CIM.T_GOOD_NAME
            //FROM      Bus_StockInVolume join T_VIEW_CIM on Bus_StockInVolume.InventoryCode=T_VIEW_CIM.T_GOOD_CODE  where DocCode='" + doccode + "' order by RowNumber  ";
            sql = @"SELECT  Bus_StockInVolume.guid, Bguid, DocCode, RowNumber, WorkShopCode, WarehouseCode, StorageLocation, T_CONTRACT_CODE, 
                T_ORDER, Bus_StockInVolume.T_GOOD_UNIT, T_GOOD_NUM, T_GOOD_PRICE, T_GOOD_MONEY, VolumeCode, InventoryCode, Size, 
                Thick, Width, Material, Weight, CID, Virtual,Address,VolumeCodeNew 
                FROM      Bus_StockInVolume 
                 where DocCode='" + doccode + "' order by RowNumber  ";
            DataTable tb1 = pub.GetDataTable(pub.ConnectionString, sql);
            uiDataGridView.AutoGenerateColumns = false;
            uiDataGridView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;

            uiDataGridView.DataSource = tb1;

            uiDataGridView.Refresh();
        }

        private DataTable List原料行信息(string doccode)
        {
            string sql;
            sql = @"SELECT Bus_StockInVolume.guid, Bguid, DocCode, RowNumber, WorkShopCode, WarehouseCode, StorageLocation, T_CONTRACT_CODE, 
                T_ORDER, Bus_StockInVolume.T_GOOD_UNIT, T_GOOD_NUM, T_GOOD_PRICE, T_GOOD_MONEY, VolumeCode, InventoryCode, Size, 
                Thick, Width, Material, Weight, CID, Virtual,Address,VolumeCodeNew ,T_VIEW_CIM.T_GOOD_NAME
                FROM      Bus_StockInVolume join T_VIEW_CIM on Bus_StockInVolume.InventoryCode=T_VIEW_CIM.T_GOOD_CODE  
                where 1=1 and DocCode='" + doccode + "' order by RowNumber  ";

            DataTable tb1 = pub.GetDataTable(pub.ConnectionString, sql);
            return tb1;
        }

        private void Delete(string doccode)
        {

            //原料的卷未被出库才能反审核
            string sql;
            sql = @"SELECT   guid, StockInType, WorkShopCode, DocCode, DepartCode, CreateID, Creator, CreateDate, ModifyID, Modifier, 
                ModifyDate, ApproverID, Approver, ApproverDate, IsSendToNC, SendToNCDate  FROM      Bus_StockInV where docCode='" + doccode + "'";
            DataTable tb = pub.GetDataTable(pub.ConnectionString, sql);
            if (tb.Rows.Count > 0)
            {
                sql = @"select guid, Bguid, DocCode, RowNumber, WorkShopCode, WarehouseCode, StorageLocation, T_CONTRACT_CODE, 
                T_ORDER, T_GOOD_UNIT, T_GOOD_NUM, T_GOOD_PRICE, T_GOOD_MONEY, VolumeCode, InventoryCode, Size, 
                Thick, Width, Material, Weight, CID, Virtual
FROM      Bus_StockInVolume where  docCode='" + doccode + "' ";

                DataTable tb2 = pub.GetDataTable(pub.ConnectionString, sql);

                if (tb2.Rows.Count > 0)
                {
                    sql = "select * from Bus_StockInVolume where  docCode='" + doccode + "' and VolumeCode in (select VolumeCode from View_PurchaseVolumeBeUsed)   ";
                    DataTable tb3 = pub.GetDataTable(pub.ConnectionString, sql);
                    if (tb3.Rows.Count > 0)
                    {
                        MessageBox.Show("该单据有行被使用了不能删除,请检查!", "提示", MessageBoxButtons.OK);
                        return;
                    } 
                }
                else
                {
                    //MessageBox.Show("该单据没有明细行,请检查!", "提示", MessageBoxButtons.OK);
                    //return;
                }
                if (tb.Rows[0]["Approver"].ToString() != "")
                {                    
                        MessageBox.Show("该单已经审核了不能删除!", "提示", MessageBoxButtons.OK);
                        return;
                                      }
                else if(tb.Rows[0]["IsSendToNC"].ToString()=="Y")
                {
                    MessageBox.Show("该单已经发送NC了不能删除!", "提示", MessageBoxButtons.OK);
                    return;
                }
            }
            else
            {
                MessageBox.Show("单据不存在，请检查!", "提示", MessageBoxButtons.OK);
                return;
            }
            if (MessageBox.Show("您要删除么?","删除确认",MessageBoxButtons.OKCancel)==DialogResult.OK)
            {
                sql = "delete Bus_StockInVolume where  docCode='" + doccode + "' ";
                sql += " delete Bus_StockInV  where  docCode='" + doccode + "'";
                pub.ExecuteSql(pub.ConnectionString, sql, "删除原料入库单");
                ListData();
            }
           

        }

        /// <summary>
        /// 反审核
        /// </summary>
        /// <param name="docCode"></param>
        /// <exception cref="NotImplementedException"></exception>

        private void DeApprove(string doccode)
        {
            //原料的卷未被出库才能反审核
            string sql;
            sql = @"SELECT   guid, StockInType, WorkShopCode, DocCode, DepartCode, CreateID, Creator, CreateDate, ModifyID, Modifier, 
                ModifyDate, ApproverID, Approver, ApproverDate, IsSendToNC, SendToNCDate  FROM      Bus_StockInV where docCode='" + doccode + "'";
            DataTable tb = pub.GetDataTable(pub.ConnectionString, sql);
            if (tb.Rows.Count > 0)
            {
                sql = @"select guid, Bguid, DocCode, RowNumber, WorkShopCode, WarehouseCode, StorageLocation, T_CONTRACT_CODE, 
                T_ORDER, T_GOOD_UNIT, T_GOOD_NUM, T_GOOD_PRICE, T_GOOD_MONEY, VolumeCode, InventoryCode, Size, 
                Thick, Width, Material, Weight, CID, Virtual
FROM      Bus_StockInVolume where  docCode='" + doccode + "' ";

                DataTable tb2 = pub.GetDataTable(pub.ConnectionString, sql);
               
                if (tb2.Rows.Count >0)
                {
                    sql = "select * from Bus_StockInVolume where  docCode='" + doccode + "' and VolumeCode in (select VolumeCode from View_PurchaseVolumeBeUsed)   ";
                    DataTable tb3 = pub.GetDataTable(pub.ConnectionString, sql);
                    if (tb3.Rows.Count >0)
                    {
                        MessageBox.Show("该单据有行被使用了不能反审核,请检查!", "提示", MessageBoxButtons.OK);
                        return;
                    }



                }
                else
                {
                    MessageBox.Show("该单据没有明细行,请检查!", "提示", MessageBoxButtons.OK);
                    return;
                }



                if (tb.Rows[0]["Approver"].ToString() != "")
                {
                    sql = "update Bus_StockInV set ApproverID='',Approver='',ApproverDate=NULL where docCode='" + doccode + "' ";
                    if (pub.ExecuteSql(pub.ConnectionString, sql,"原料入库单反审核") > 0)
                    {
                        MessageBox.Show("反审核成功!", "提示", MessageBoxButtons.OK);
                        ListData();
                        return;
                    }
                }
                else
                {
                    MessageBox.Show("尚未审核了，不能反审核!", "提示", MessageBoxButtons.OK);
                    return;
                }
            }
            else
            {
                MessageBox.Show("单据不存在，请检查!", "提示", MessageBoxButtons.OK);
                return;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="doccode"></param>
        /// <exception cref="NotImplementedException"></exception>
        private void Approve(string doccode)
        {
            string sql;
            sql = @"SELECT   guid, StockInType, WorkShopCode, DocCode, DepartCode, CreateID, Creator, CreateDate, ModifyID, Modifier, 
                ModifyDate, ApproverID, Approver, ApproverDate, IsSendToNC, SendToNCDate  FROM      Bus_StockInV where docCode='" + doccode + "'";
            DataTable tb = pub.GetDataTable(pub.ConnectionString, sql);
            if (tb.Rows.Count >0)
            {
                if (tb.Rows[0]["Approver"].ToString()=="")
                {
                    sql = "update Bus_StockInV set ApproverID='" + pub.sys_user.User_Id + "',Approver='" + pub.sys_user.UserName + "',ApproverDate=getdate() where docCode='" + doccode + "' ";
                    if (pub.ExecuteSql(pub.ConnectionString,sql,"原料入库单审核")>0)
                    {
                        MessageBox.Show("审核成功!", "提示", MessageBoxButtons.OK);
                        ///更新Bus_Volume信息
                       
                        ListData();
                        return;
                    }
                }
                else
                {
                    MessageBox.Show("已经审核了，不能再次审核!", "提示", MessageBoxButtons.OK);
                    return;
                }
            }
            else
            {
                MessageBox.Show("单据不存在，请检查!", "提示", MessageBoxButtons.OK);
                return;
            }
        }

        private void uiDataGridView原料入库单_Click(object sender, EventArgs e)
        {
            
        }

        private void uiDataGridView原料入库单_CellContentClick_1(object sender, DataGridViewCellEventArgs e)
        {

            if (e.RowIndex >= 0)
            {
                docCode = this.uiDataGridView原料入库单.Rows[e.RowIndex].Cells["C入库单号"].Value.ToString();
                List原料行信息(docCode, this.uiDataGridView合同原料卷);

                if (this.uiDataGridView原料入库单.Columns[e.ColumnIndex].Name == "C审核")
                {
                    //
                    Approve(docCode);
                }
                else if (this.uiDataGridView原料入库单.Columns[e.ColumnIndex].Name == "C反审核")
                {
                    DeApprove(docCode);

                }
                else if (this.uiDataGridView原料入库单.Columns[e.ColumnIndex].Name == "C删除")
                {
                    Delete(docCode);
                }
                else if (this.uiDataGridView原料入库单.Columns[e.ColumnIndex].Name == "C发送NC")
                {
                    ///待完成
                    sendToNC(docCode);
                    ListData();
                }
            }
        }

        private void sendToNC(string docCode)
        {
            string sql;
            sql = @"SELECT guid, StockInType, WorkShopCode, DocCode, DepartCode, SupplierCode, SupplierName, CreateID, Creator, 
                   CreateDate, ModifyID, Modifier, ModifyDate, ApproverID, Approver, ApproverDate, IsSendToNC, SendToNCDate
                   FROM      Bus_StockInV where docCode='" + docCode + "'";
            DataTable dtHeader = pub.GetDataTable(pub.ConnectionString, sql);

            if (dtHeader != null && dtHeader.Rows.Count > 0)
            {
                DataTable dtBody = List原料行信息(docCode);
                if (dtBody != null && dtBody.Rows.Count > 0)
                {
                    List<Bus_StockInV> bus_StockInVs = pub.GetTableToList<Bus_StockInV>(dtHeader);

                    NCModel.SetInboundModel setInboundModel = new NCModel.SetInboundModel();
                    setInboundModel.dBillDate = bus_StockInVs[0].CreateDate.GetValueOrDefault().ToString("yyyy-MM-dd");
                    //仓库 地区 供应商先写死
                    setInboundModel.supplierName = "温州常展电气科技有限公司";
                    setInboundModel.supplierCode = "0577-WJ-0207";
                    //查询公司名称 公司编号
                    string sqlworkshop = @"SELECT  [WorkShopName]  FROM [Dic_WorkShop] where WorkShopCode = '" + bus_StockInVs[0].WorkShopCode + "'";
                    DataTable dtWorkShop = pub.GetDataTable(pub.ConnectionString, sqlworkshop);
                    if (dtWorkShop != null && dtWorkShop.Rows.Count > 0)
                    {
                        setInboundModel.corpName = dtWorkShop.Rows[0]["WorkShopName"].ToString();
                    }
                    else
                    {
                        MessageBox.Show("未能根据当前入库单公司编号查到对应的公司名称");
                        return;
                    }
                    //仓库 地区 供应商先写死
                    setInboundModel.region = "华东";
                    setInboundModel.warehouse = 仓库名称;

                    List<NCModel.SetInboundItem> itemList = new List<NCModel.SetInboundItem>();
                    for (int i = 0; i < dtBody.Rows.Count; i++)
                    {
                        NCModel.SetInboundItem item = new NCModel.SetInboundItem();
                        item.rowNo =  Guid.NewGuid().ToString(); 
                        item.itemCode = dtBody.Rows[i]["InventoryCode"].ToString();
                        item.unit = dtBody.Rows[i]["T_GOOD_UNIT"].ToString();
                        //热轧类物料需要产地信息
                        item.vfree3 = dtBody.Rows[i]["Address"].ToString();
                        item.nnum = dtBody.Rows[i]["Weight"].ToString();
                        item.ncLot = dtBody.Rows[i]["VolumeCodeNew"].ToString();
                        item.vuserdef6 = dtBody.Rows[i]["VolumeCode"].ToString();
                        item.nastnum = "1";
                        item.vuserdef7 = dtBody.Rows[i]["DocCode"].ToString();
                        item.vuserdef9 = dtBody.Rows[i]["StorageLocation"].ToString();

                        itemList.Add(item);
                    }
                    setInboundModel.items = itemList;
                    string jsonStr = JsonConvert.SerializeObject(setInboundModel);
                    //XmlDocument xml  = (XmlDocument)JsonConvert.DeserializeXmlNode(jsonStr,"root");
                    ExternalSystemToNcItfPortTypeClient client = new ExternalSystemToNcItfPortTypeClient();
                    string responseStr = client.setInbound(jsonStr);
                    NCModel.NCResponseModel nCResponse = JsonConvert.DeserializeObject<NCModel.NCResponseModel>(responseStr);
                    //调用成功，改写NC状态
                    if (nCResponse.state == 0)
                    {
                        string sqlUpdate = @"update Bus_StockInV set IsSendToNC = 'Y' ,SendToNCDate = '" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "',SendToNCReturnValue = '"+ nCResponse.result+ "' where docCode = '" + docCode + "'";
                        int r = pub.ExecuteSql(pub.ConnectionString, sqlUpdate, "原料卷入库发送到NC");
                        if (r < 1)
                        {
                            MessageBox.Show("更新是否成功发送到NC失败");
                        }
                    }
                    MessageBox.Show(nCResponse.msg);

                }
                else
                {
                    MessageBox.Show("没查到行信息");
                }
            }
            else
            {
                MessageBox.Show("没查到对应原材料入库单");
            }
        }
    }
}
